

void load(lua_State *L, const char* fname, int *w, int *h) {
  if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0)) {
    error(L, "cannot run config.file :%s", lua_tostring(L, -1));
  }
  lua_getglobal(L, "width");
  lua_getglobal(L, "height");
  if (!lua_isnumber(L, -2))
    error(L, "'witdh' should be a number \n");
  if (!lua_isnumber(L, -1))
    error(L, "'height' should be a number\n");
  *w = lua_tointeger(L, -2);
  *h = lua_tointeger(L, -1);

  lua_getglobal(L, "background");
  if (!lua_istable(L, -1))
    error(L, "'background' is not a table");
  int red = getfield(L, "r");
  int green = getfield(L, "g");
  int blue = getfield(L, "b");
}

#define MAX_COLOR 0xFF

int getfield(lua_State *L, const char *key) {
  int result;
  lua_getfield(L, -1, key);
  if (!lua_isnumber(L, -1))
    error(L, "invaild component in background color");
  result = (int)lua_tonumber(L, -1) * MAX_COLOR;
  lua_pop(L, 1);
  return result;
}

struct ColorTable {
  char *name;
  unsigned char red, green, blue;
} colortable[] = {
  {"WHITE", MAX_COLOR, MAX_COLOR, MAX_COLOR},
  {"RED", MAX_COLOR, 0, 0},
  {"GREEN", 0, MAX_COLOR, 0},
  {"BLUE", 0, 0, MAX_COLOR},
  {NULL, 0, 0, 0}
};

void setfield(lua_State *L, const char* index, int value) {
  lua_pushnumber(L, (double)value/MAX_COLOR);
  lua_settable(L, -2, index);
}

void setcolor(lua_State *L, struct ColorTable *ct) {
  lua_newtable(L);
  setfield(L, "r", ct->red);
  setfield(L, "g", ct->green);
  setfield(L, "b", ct->blue);
  lua_setglobal(L, ct->name);
}
